<template>
  <el-upload class="avatar-uploader" :show-file-list="false" :http-request="handleUpload"
    :before-upload="beforeAvatarUpload">
    <img v-if="imageUrl || preview" :src="imageUrl || preview" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script>
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import AV from "leancloud-storage";
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default {
  props: ["preview"],
  data() {
    return {
      imageUrl: "",
    };
  },
  methods: {
    // 自定义图片上传方法
    handleUpload(info) {
      // console.log(info); //1. 获取到的本地文件资源对象
      // 2. 将文件对象变为base64编码
      getBase64(info.file, (base64) => {
        // console.log(base64);
        const data = { base64 };
        // 3. 将base64编码转化为LeanCloud资源
        const file = new AV.File("vue-img.png", data);
        // 4. 保存图片到LeanCloud
        file.save().then((res) => {
          console.log(res);
          let { url } = res.attributes;
          this.imageUrl = url;
          this.$emit("update:modelValue", url); //将图片路径传给父级
        });
      });
    },
    // 文件类型的判断
    beforeAvatarUpload(rawFile) {
      console.log(rawFile.type);
      let isImg = rawFile.type == "image/jpeg" || rawFile.type == "image/png";
      let is2M = rawFile.size / 1024 / 1024 < 2;
      if (!isImg || !is2M) {
        ElMessage.error("图片必须是jpg/png,且不大于2M!");
        return false;
      }
      return true;
    },
  },
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
